import * as React from 'react';
import { connect } from 'react-redux';
import { Modal, Button, Tabs, Icon, message } from 'antd';
import { get, upperFirst, camelCase } from 'lodash';

import TestParserPlugins from 'components/review-test-parser/index';

import { isLoading } from 'utils/utils';
import ACTIONS from 'constants/review';

import { fetchTestDetail, fetchTestTplList, removeTest } from 'actions/review';
import LoadableComponent from 'components/common/LoadableComponent';
const LoadableEditBasic = LoadableComponent(() => import('./EditBasic'));

// name对应DB数据
// Ref对应本地模板名称
const tpls = [
  {
    name: 'template1',
    ref: 'Tpl1',
  },
];
function getPluginRef(tplName: string) {
  const tpl = tpls.find((item: any) => {
    return item.name === tplName;
  });
  return tpl ? tpl.ref : '';
}

interface EditProps {
  dispatch: (action: any) => any;
  onCreateCallback: (id: any) => any;
  onRemoveCallback: () => any;
  testId: any;
  loadingGroup: any;
}

interface EditState {
  editTest: any;
  activeKey: string;
  tpls: any[];
}

class Edit extends React.Component<EditProps, EditState> {
  basicCounter: number;
  static defaultProps: EditProps = {
    dispatch: () => {},
    onCreateCallback: () => {},
    onRemoveCallback: () => {},
    testId: 0,
    loadingGroup: {},
  };
  constructor(props: EditProps) {
    super(props);
    this.state = {
      activeKey: 'basic',
      editTest: {
        id: 1,
        name: 'test 1',
        templateId: 1,
      },
      tpls: [
        {
          id: 1,
          name: 'template1',
        },
      ],
    };
    this.basicCounter = 0;
  }

  componentWillMount() {
    const { testId, dispatch } = this.props;
    if (testId) {
      this.handleFetchTestDetail();
    }

    const filters = {
      page: 1,
      pageSize: 99,
    };
    dispatch(fetchTestTplList(filters)).then((result: any) => {
      if (result.code) {
        message.error(result.msg);
      } else {
        this.setState({
          tpls: get(result, 'response.data.items', []),
        });
      }
    });
  }

  componentWillReceiveProps(nextProps: any) {
    const { testId } = nextProps;
    const { testId: oldTestId } = this.props;
    if (testId !== oldTestId) {
      if (testId) {
        this.handleFetchTestDetail(testId);
      }
      if (this.state.activeKey !== 'basic') {
        this.handleChangeTab('basic');
      }
    }
  }

  handleRemoveTest = () => {
    const { dispatch, testId, loadingGroup, onRemoveCallback } = this.props;

    if (testId && !isLoading(loadingGroup, ACTIONS.REMOVE_TEST)) {
      Modal.confirm({
        title: '危险',
        content: '你确定要删除此试题及相关数据吗？',
        okText: '确定',
        cancelText: '取消',
        iconType: 'info-circle',
        onOk: () => {
          dispatch(removeTest(testId)).then((result: any) => {
            if (result.code) {
              message.error(result.msg);
            } else {
              message.success('试题删除成功');
              onRemoveCallback();
            }
          });
        },
      });
    }
  };

  handleFetchTestDetail = (testId: number = this.props.testId) => {
    const { dispatch } = this.props;
    dispatch(fetchTestDetail(testId)).then((result: any) => {
      if (result.code) {
        message.error(result.msg);
      } else {
        this.setState({
          editTest: result.response.data,
        });
      }
    });
  };

  handleChangeTab = (activeKey: string) => {
    this.setState({
      activeKey,
    });
  };

  render() {
    let TestParser = null;
    const plugins = TestParserPlugins;
    let { onCreateCallback, testId } = this.props;
    let { activeKey, tpls, editTest } = this.state;

    editTest = testId ? editTest : null;
    const isNewRecord = !editTest;

    if (typeof plugins === 'object') {
      try {
        let pluginName = '';
        if (editTest && tpls.length) {
          const tpl = tpls.find((item: any) => {
            return item.id === editTest.templateId;
          });
          if (tpl) {
            pluginName = getPluginRef(tpl.name);
          }
        }

        if (pluginName) {
          pluginName = upperFirst(camelCase(pluginName));
        }

        if (plugins[pluginName]) {
          TestParser = plugins[pluginName];
        } else {
          TestParser = plugins.Default;
        }
      } catch (e) {
        console.warn(e.message);

        TestParser = plugins.Default;
      }
    }

    return (
      <Tabs size="small" animated={false} onChange={this.handleChangeTab} activeKey={activeKey}>
        <Tabs.TabPane
          tab={
            <p>
              <Icon type={isNewRecord ? 'plus' : 'edit'} />
              {isNewRecord ? '新增' : '修改'}
              &nbsp;评测试题
            </p>
          }
          key="basic">
          <LoadableEditBasic
            editTest={editTest}
            tpls={tpls}
            onCreateCallback={onCreateCallback}
            onRemoveCallback={this.handleRemoveTest}
            key={`basic_info_${this.basicCounter}`}
          />
        </Tabs.TabPane>
        <Tabs.TabPane
          tab={
            <p>
              <Icon type={isNewRecord ? 'lock' : 'code-o'} />试题内容
            </p>
          }
          key="template"
          disabled={isNewRecord}>
          <TestParser test={editTest} fetchTestDetail={this.handleFetchTestDetail} />
        </Tabs.TabPane>
      </Tabs>
    );
  }
}

interface OwnProps {
  testId: number;
}
function mapStateToProps(state: any, ownProps: OwnProps) {
  const { testId } = ownProps;
  const { loadingGroup } = state;

  return {
    testId,
    loadingGroup,
  };
}

export default connect(mapStateToProps)(Edit);
